const getProductSortUrl = "https://ali.ikenway.net:18443/api/productSort/findAll";
const getProductUrl = "https://ali.ikenway.net:18443/api/product/findAll";

const createProductUrl = "https://ali.ikenway.net:18443/api/product/create";
const deleteProductUrl = "https://ali.ikenway.net:18443/api/product/delete";
const updateProductUrl = "https://ali.ikenway.net:18443/api/product/update";

const picUploadUrl = "https://ali.ikenway.net:18443/api/upload";

let productSorts = null;
let products = null;
let token = sessionStorage.getItem("token");
let sortSelectorOptions = "";

function initProductSorts() {

    fetch(getProductSortUrl, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token
        }
    }).then(res => {
        res.json().then(json => {
            if (json.code === 200) {
                productSorts = json.data;

                for (let i = 0; i < productSorts.length; i++) {
                    sortSelectorOptions += `
                        <option value="` + productSorts[i].sortId + `">` + productSorts[i].sortName + `</option>
                    `;
                }

                document.getElementById("modal-selector").innerHTML = sortSelectorOptions;


                initProducts(sortSelectorOptions)
            } else if (json.code === 400) {
                alertMsg(json.msg);

                window.location.href = loginPageUrl;
            } else {
                alertMsg(json.msg);
            }
        })
    })
}

function initProducts(sortSelectorOptions = "") {
    let tableInnerHtml = "";

    fetch(getProductUrl, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token
        }
    }).then(res => {
        res.json().then(json => {
            if (json.code === 200) {
                products = json.data;

                for (let i = 0; i < products.length; i++) {
                    let deleted = "";
                    if (products[i].deleted) deleted = "disabled";

                    tableInnerHtml += `
                        <tr class="table-row-` + i + `">
                            <td>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" value="` + i + `" ` + deleted + `>
                                </div>
                            </td>
                            <th scope="row">` + products[i].productId + `</th>
                            <td>
                                <label class="w-75">
                                    <input type="text" class="form-control" value="` + products[i].productName + `">
                                </label>
                            </td>
                            <td>
                                <select class="form-select me-3" aria-label="Default select example" style="width: 180px">
                                    <option value="` + products[i].sortId + `" selected>` + products[i].sortName + ` (原分类)</option>
                                    ` + sortSelectorOptions + `
                                </select>
                            </td>
                            <td>
                                <label class="w-50">
                                    <input type="text" class="form-control" value="` + products[i].mediumPrice + `">
                                </label>
                            </td>
                            <td>
                                <label class="w-50">
                                    <input type="text" class="form-control" value="` + products[i].largePrice + `">
                                </label>
                            </td>
                            <td>
                                <label class="w-50">
                                    <input type="text" class="form-control" value="` + products[i].disCount + `" disabled>
                                </label>
                            </td>
                            <td class="d-flex flex-row align-items-baseline mb-0">
                                <button type="button" class="btn btn-primary me-3 ` + deleted + `" onclick="productEdit(` + i + `)" >修改</button>
                                <button type="button" class="btn btn-info me-3 ` + deleted + `" data-bs-toggle="modal"
                                    data-bs-target="#productPreviewModal" data-bs-index="` + i + `">预览图</button>
                                <button type="button" class="btn btn-danger ` + deleted + `" onclick="productOpera(` + i + `)">删除</button>
                            </td>
                        </tr>
                    `;
                }

                document.getElementById("table-body").innerHTML = tableInnerHtml;
            } else if (json.code === 400) {
                alertMsg(json.msg);

                window.location.href = loginPageUrl;
            } else {
                if (json.msg != null) {
                    alertMsg(json.msg);
                } else {
                    alertMsg("发生未知错误");
                }
            }
        })
    })

}

function productCreate() {
    let selector = document.getElementById("modal-selector");

    let data = {
        "productName": document.getElementById("input1").value,
        "sortId": selector.options[selector.selectedIndex].value,
        "mediumPrice": document.getElementById("input2").value,
        "largePrice": document.getElementById("input3").value,
    }

    fetch(createProductUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token
        },
        body: JSON.stringify(data)
    }).then(res => {
        res.json().then(json => {
            if (json.code === 400) {
                alertMsg(json.msg);

                window.location.href = loginPageUrl;
            }
            alertMsg(json.msg);
        })
    })
}

function productOpera() {
    switch (document.getElementById("selector").selectedIndex) {
        case 0:
            productDelete();
            break;
        case 1:
            break;
    }
}

function productDelete(index = null) {
    let formCheck = document.querySelectorAll(".form-check-input");
    let data = null;

    if (index !== null) {
        data = {
            "productIds": [products[index].productId]
        };
    } else {
        let checked = [];

        for (let i = 0; i < formCheck.length; i++) {
            if (formCheck[i].checked) {
                checked.push(products[formCheck[i].value].productId);
            }
        }

        data = {
            "productIds": checked
        }

    }

    fetch(deleteProductUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token
        },
        body: JSON.stringify(data)
    }).then(res => {
        res.json().then(json => {
            if (json.code === 400) {
                alertMsg(json.msg);

                window.location.href = loginPageUrl;
            }
            alertMsg(json.msg);
        })
    });
}

function productEdit(index) {
    let col = document.querySelectorAll(".table-row-" + index + " .form-control");

    let selector = document.querySelector(".table-row-" + index + " .form-select");

    let sortId = selector.options[selector.selectedIndex].value

    let data = {
        "productId": products[index].productId,
        "productName": col[0].value,
        "sortId": sortId,
        "preview": products[index].preview,
        "mediumPrice": col[1].value,
        "largePrice": col[2].value,
    };

    fetch(updateProductUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token
        },
        body: JSON.stringify(data)
    }).then(res => {
        res.json().then(json => {
            if (json.code === 400) {
                alertMsg(json.msg);

                window.location.href = loginPageUrl;
            }
            alertMsg(json.msg);
        });
    })
}

function initModal() {
    let modal = document.getElementById("productPreviewModal");
    modal.addEventListener("show.bs.modal", function (event) {
        let index = event.relatedTarget.getAttribute('data-bs-index');
        document.getElementById("preview").src = products[index].preview == null ? "img/camera.png" : products[index].preview;
        document.getElementById("inputFile").onchange = function () {
            productPreviewUpload(index);
        }
    })
}

function productPreviewUpload(index = null) {
    let file = document.getElementById("inputFile").files[0];
    let data = new FormData();

    data.append("file", file);

    fetch(picUploadUrl, {
        method: 'POST',
        headers: {
            'Authorization': token
        },
        body: data
    }).then(res => {
        res.json().then(json => {
            console.log(json);

            alertMsg(json.msg);

            if (json.code === 200) {
                document.getElementById("save").onclick = function () {
                    productPreviewUpdate(index, json.data.url)
                }
            }
        })
    });
}

function productPreviewUpdate(index, url) {
    let product = products[index];
    product.preview = url;

    fetch(updateProductUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token
        },
        body: JSON.stringify(product)
    }).then(res => {
        res.json().then(json => {
            if (json.code === 400) {
                alertMsg(json.msg);

                window.location.href = loginPageUrl;
            }
            alertMsg(json.msg);
        })
    })
}
